﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using System.Text;
using System.IO;
using CMN.Framework;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using CMN.Models;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Normal_UploadImageController : Controller
    {

        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index(string actionId)
        {
            IDataService<Normal_ThumbnailEntity> thumbnailSv = ServiceBuilder.BuildNormal_ThumbnailService();
            QueryParam qp=new QueryParam();
            qp.PageSize=200;
            int recordCount=0;
            List<Normal_ThumbnailEntity> thumbs = thumbnailSv.List(qp, out recordCount);
            ViewData["thumbs"] = thumbs;
            IDataService<Normal_ChannelEntity> channelSv = ServiceBuilder.BuildNormal_ChannelService();
            qp.PageSize = 1;
            Normal_ChannelEntity channel=channelSv.Look(Utils.StringToInt(actionId,0));
            if (channel != null)
            {
                ViewData["defaultThumbs"] = channel.DefaultThumbs;
            }
            string[] strs = actionId.Split(new string[] { "_" }, StringSplitOptions.None);
            if (strs.Length == 2)
            {
                ViewData["id"] = strs[0];
                ViewData["type"] = strs[1];
            }
            else
            {
                ViewData["id"] = string.Empty;
                ViewData["type"] = string.Empty; ;
            }
            return View("Index");//页面地址
        }


        /// <summary>
        /// 返回功能模块列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
           
            return returnJson;

        }
       

        /// <summary>
        /// 查看频道 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
            return returnJson;
        }

        /// <summary>
        /// 更新频道
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {
            //上传文件
            HttpPostedFileBase file = Request.Files["Filedata"];

            // string uploadPath =               HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";
           
            if (file != null)
            {
                string uploadPath = string.Concat("/Upload/Image/");
                string path = Server.MapPath(uploadPath);
                string name = string.Concat(UserData.GetUserData.UserID.ToString(), System.IO.Path.GetExtension(file.FileName).ToLower());
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                file.SaveAs(string.Concat(path, name));
                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失

                return string.Concat(uploadPath, name);
            }
            else
            {
                return "0";
            }
            return returnJson;
        }

        /// <summary>
        /// 新增频道
        /// </summary>
        /// <returns>json</returns>
        public string Insert(string actionId)
        {
            string methodName = Request["action"];
            string src = Request["src"];
            while (src.StartsWith("/"))
            {
                src = src.Substring(1);
            }
            src = string.Concat(Server.MapPath("~/"), src);
            if (methodName == "RotateBitmap")
            {
               returnJson= RotateBitmap(src);
            }
            else if (methodName == "GenerateBitmap")
            {
               returnJson= GenerateBitmap(src);
            }
            else
            {
                returnJson = "{msg:'错误的方法'}";
            }
           
            return returnJson;
        }

        protected  string RotateBitmap(string src)
        {
            try
            {
                float angle = float.Parse(Request["angle"]);
                Image oldImage = Bitmap.FromFile(src);
                ImageHelper imgHelper = new ImageHelper();
                
                Bitmap newBmp = imgHelper.RotateImage(oldImage, angle);
                oldImage.Dispose();
                int nw = newBmp.Width;
                int nh = newBmp.Height;
                newBmp.Save(src);
                newBmp.Dispose();
                return "{msg:'success',size:{width:" + nw.ToString() + ",height:" + nh.ToString() + "}}";
            }
            catch (Exception ex)
            {
                return "{msg:'" + ex.Message + "'}";
            }
        }

        protected  string GenerateBitmap(string src)
        {
            try
            {
                FileInfo fi = new FileInfo(src);
                string ext = fi.Extension;
                string uploadPath = string.Concat("/Upload/Image/", DateTime.Now.Year.ToString(), "/", DateTime.Now.Month.ToString(), "/", DateTime.Now.Day, "/");
                string path = Server.MapPath(uploadPath);
                string name = string.Concat(Guid.NewGuid().ToString("N") , ".png");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失

                string newfileName = string.Concat(uploadPath, name);

                //Image.GetThumbnailImageAbort abort = null;
                Bitmap oldBitmap = new Bitmap(src);

                Cutter cut = new Cutter(
                    double.Parse(Request["zoom"]),
                    -int.Parse(Request["x"]),
                    -int.Parse(Request["y"]),
                    int.Parse(Request["width"]),
                    int.Parse(Request["height"]),
                    oldBitmap.Width,
                    oldBitmap.Height);
                ImageHelper imgHelper = new ImageHelper();
                Bitmap bmp = imgHelper.GenerateBitmap(oldBitmap, cut);
                oldBitmap.Dispose();

                string temp = Server.MapPath(newfileName);
                bmp.Save(temp, ImageFormat.Png);
                bmp.Dispose();
                return "{msg:'success',src:'" + newfileName + "'}";
            }
            catch (Exception ex)
            {
                return "{msg:'" + ex.Message + "'}";
            }
        }

        /// <summary>
        /// 删除频道
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            return returnJson;
        }

        /// <summary>
        /// 批量删除频道
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {

            return returnJson;
        }

    }
}
